const { dateFormat } = require('./utils.js');
const shell = require('shelljs');
const path = require('path');
const Client = require('ssh2-sftp-client');
const chalk = require('chalk');
const inquirer = require('inquirer');

const compileDist = async () => {
	if (shell.exec('npm run build:dev').code === 0) {
		console.log(chalk.cyan('打包成功\n'));
	}
};
async function connectShell(projectName, config) {
	let projectInfo = {
		'win-term-ui': [
			{
				ip: '192.168.8.102', // 主机ip地址
				username: 'dever', // ssh用户名
				port: '222', // ssh端口号
				password: 'gNk!1j6@3y7O', // ssh密码
				path: '/home/dever/win/html/win_term', // 操作文件夹的配置地址路径
				uploadpath: '../dist/win_term' // 上传文件夹地址路径
			}
		],
		'casehub-vue-ui': [
			{
				ip: '192.168.8.102', // 主机ip地址
				username: 'dever', // ssh用户名
				port: '222', // ssh端口号
				password: 'gNk!1j6@3y7O', // ssh密码
				path: '/home/dever/guochuang/html', // 操作文件夹的配置地址路径
				uploadpath: '../dist' // 上传文件夹地址路径
			}
		]
	};
	(projectInfo[projectName] || config).map(item => {
		const sftp = new Client();
		sftp
			.connect({
				host: item.ip,
				port: item.port,
				username: item.username,
				password: item.password
			})
			.then(() => {
				console.log(chalk.green('\n先执行拉下文件备份\n'));
				return sftp.downloadDir(
					item.path,
					path.resolve('__dirname', `../dist1/${dateFormat(new Date())}`)
				);
			})
			.then(() => {
				console.log(chalk.green('执行删除文件\n'));
				return sftp.rmdir(item.path, true);
			})
			.then(() => {
				console.log(chalk.green('执行上传文件\n'));
				return sftp.uploadDir(
					path.resolve('__dirname', `${item.uploadpath}`),
					item.path
				);
			})
			.then(() => {
				console.log(chalk.green('上传完成\n'));
				sftp.end();
			})
			.catch(err => {
				console.log(chalk.red.bold(err, '上传失败'));
				sftp.end();
			});
	});
}
export async function runStart(projectName, config) {
	inquirer
		.prompt([
			{
				type: 'list',
				name: 'list',
				message: '是否先进行打包？？？',
				choices: [
					{
						name: '打包',
						value: true
					},
					{
						name: '不打包',
						value: false
					}
				]
			}
		])
		.then(async answers => {
			if (answers.list) {
				await compileDist();
				await connectShell(projectName, config);
			} else {
				await connectShell(projectName, config);
			}
		});
}
